/**
 * 字段配置记录
 */
import React from 'react';
import { Table, Form, Radio, DatePicker, message } from 'antd';
import { history } from 'umi'
import moment from 'moment';
import { isArray } from 'lodash';
import { PageContainer } from '@/molecules';
import { Pagination } from '@/components';
import { useRequest } from '@/hooks';
import { getChannelListWithoutTalent, getFieldSetRecord } from './service';

const operateTypeList = {
    1: '添加',
    2: '修改',
    3: '删除'
};

function FieldSetRecord({ form, location }) {
    const { query = {} } = location;
    const { getFieldDecorator } = form;
    const { data, loading, run } = useRequest(getFieldSetRecord, {
        manual: true
    });
    const dataSource = data?.data?.rows || [];
    const total = data?.data?.total || 0;

    const { data: channelList } = useRequest(() => getChannelListWithoutTalent({ channelStatus: 1, channelType: 2 }), {
        initialData: [],
        formatResult: res => {
            if (res) {
                const { code, data: temp, msg } = res;
                if (code === 10000) {
                    return temp.map(item => ({
                        text: item.channelName,
                        value: item.channelCode
                    }));
                }
                message.error(msg);
            }
            return [];
        }
    });

    React.useEffect(() => {
        const { orderByField = '', startDate, endDate, channelCode = [], dateQuick, ...rest } = query;
        const channelCodes = isArray(channelCode) ? channelCode : [channelCode];
        run({
            ...rest,
            startDate:
                startDate ||
                moment()
                    .subtract(6, 'days')
                    .format('YYYY-MM-DD'),
            endDate: endDate || moment().format('YYYY-MM-DD'),
            orderByField: orderByField.replace('end', ''),
            channelCodeList: channelCodes
        });
    }, [query]);

    const columns = [
        {
            title: '渠道',
            dataIndex: 'channelName',
            width: 140,
            filteredValue:
                query?.channelCode && (isArray(query?.channelCode) ? query?.channelCode : [query?.channelCode]),
            filters: channelList
        },
        {
            title: '配置人',
            width: 120,
            ellipsis: true,
            dataIndex: 'operateUserName'
        },
        {
            title: '操作',
            dataIndex: 'operateType',
            width: 80,
            render: text => operateTypeList[text] || ''
        },
        {
            title: '时间',
            dataIndex: 'operateTime',
            width: 150,
            sortOrder: query.orderByField ? query.orderByField.split('|')[1] : undefined,
            sorter: () => {},
            render: text => (text ? moment(text).format('YYYY-MM-DD HH:mm') : text)
        },
        {
            title: '招聘职位',
            dataIndex: 'positionName',
            ellipsis: true
        },
        {
            title: '配置信息',
            dataIndex: 'operateContent',
            ellipsis: true
        }
    ];

    const handlePaginationChange = pagination => {
        const { current, pageSize } = pagination;
        history.push({ query: { ...query, pageNo: current, pageSize } });
    };

    const handleTableChange = (_, filters = {}, sorter) => {
        const { channelName } = filters;
        const { field, order } = sorter;
        history.push({
            query: {
                ...query,
                channelCode: channelName,
                orderByField: order ? `${field}|${order}` : '',
                pageNo: 1
            }
        });
    };

    const handleSubmit = () => {
        const params = form.getFieldsValue();
        const { rangeTime = [], ...rest } = params;
        const finalParams = {
            ...rest,
            startDate: rangeTime.length > 0 ? rangeTime[0]?.format('YYYY-MM-DD') : '',
            endDate: rangeTime.length > 1 ? rangeTime[1]?.format('YYYY-MM-DD') : '',
            pageNo: 1
        };
        history.push({ query: { ...query, ...finalParams } });
    };

    const getDefaultRangeTime = () => [moment().subtract(6, 'days'), moment()];

    const handleQuickDate = e => {
        if (!e.target.value) {
            return;
        }
        const arr = e.target.value.split(',');
        const start = arr[0];
        const duration = arr[1];
        const startDate = moment().subtract(Number(start) + Number(duration) - 1, 'days');
        const endDate = moment().subtract(Number(start), 'days');
        form.setFieldsValue({
            dateQuick: e.target.value,
            rangeTime: [startDate, endDate]
        });
        handleSubmit();
    };

    const handleDateChange = date => {
        form.setFieldsValue({
            dateQuick: undefined,
            rangeTime: date
        });
        handleSubmit();
    };

    return (
        <PageContainer>
            <Form layout="inline" onSubmit={handleSubmit} style={{ marginBottom: 16 }}>
                <Form.Item label="时间" style={{ display: 'block' }}>
                    {getFieldDecorator('dateQuick', {
                        initialValue: query?.startDate ? query?.dateQuick : query?.dateQuick || '0,7'
                    })(
                        <Radio.Group onChange={handleQuickDate} style={{ marginRight: 12 }}>
                            <Radio.Button value="0,1">今天</Radio.Button>
                            <Radio.Button value="1,1">昨天</Radio.Button>
                            <Radio.Button value="0,7">近七天</Radio.Button>
                            <Radio.Button value="0,30">近30天</Radio.Button>
                        </Radio.Group>
                    )}
                    {getFieldDecorator('rangeTime', {
                        initialValue:
                            (query?.startDate &&
                                query?.endDate && [moment(query?.startDate), moment(query?.endDate)]) ||
                            getDefaultRangeTime()
                    })(
                        <DatePicker.RangePicker allowClear={false} style={{ width: 250 }} onChange={handleDateChange} />
                    )}
                </Form.Item>
            </Form>
            <Table
                rowKey="operateTime"
                columns={columns}
                dataSource={dataSource}
                pagination={false}
                scroll={{ x: 'max-content' }}
                onChange={handleTableChange}
                loading={loading}
            />
            <Pagination
                current={query?.pageNo || 1}
                pageSize={query?.pageSize || 10}
                loading={loading}
                total={total || 0}
                onChange={handlePaginationChange}
            />
        </PageContainer>
    );
}

export default Form.create()(FieldSetRecord);
